package com.thread.example.handleList;

import org.apache.commons.lang3.ArrayUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Java多线程处理List数据 https://www.cnblogs.com/huangdabing/p/9251598.html
 * 多线程数量的问题，一般情况下，多线程数量要等于机器CPU核数-1.
 * 实例1：
 *  解决问题：如何让 n个线程 按顺序 遍历 含有M个元素的List集合
 */
public class Test_1 {
    /**
     * 多线程处理list
     *
     * @param dataList      数据list
     * @param threadNum 线程数
     */
    public synchronized void handleList(List<String> dataList, int threadNum) {
        int length = dataList.size();
        int pageSize = length % threadNum == 0
                ?  length / threadNum
                : (length / threadNum + 1);

        for (int i = 0; i < threadNum; i++) {
            int pageNo = i + 1;//当前页
            int offset_end = pageNo * pageSize;//当前页末尾行的索引
            HandleThread thread = new HandleThread(
                    "线程[" + pageNo + "] ",
                    dataList,
                    i * pageSize,
                    offset_end > length ? length : offset_end
            );
            thread.start();
        }
    }

    class HandleThread extends Thread {
        private String threadName;
        private List<String> data;
        private int listSubStart;
        private int listSubEnd;

        public HandleThread(String threadName, List<String> data, int listSubStart, int listSubEnd) {
            this.threadName = threadName;
            this.data = data;
            this.listSubStart = listSubStart;
            this.listSubEnd = listSubEnd;
        }

        public void run() {
            List<String> subList = data.subList(listSubStart, listSubEnd)/*.add("^&*")*/;
            System.out.println(threadName + "处理了" + subList.size() + "条！");
        }

    }

    public static void main(String[] args) {
        Test_1 test = new Test_1();
        // 准备数据
        List<String> data = new ArrayList<String>();
        for (int i = 0; i < 20; i++) {
            data.add("item" + i);
        }
        test.handleList(data, 5);
        System.out.println(ArrayUtils.toString(data));

    }
}
